function PageTools() {
	this.judge = new JudgeFunc();
	this.tool=new ToolsFunc();
	this.image=new ToolsImage();
}

/**
 * 用于判断操作
 */
function JudgeFunc() { }

/**
 * 辅助工具
 */
function ToolsFunc() { }

/**
 * 图片操作工具
 */
function ToolsImage() { }


/*********************************JudgeFunc*******************************************************
/**
 * 判断是否不为Defined，切不为Null
 */
JudgeFunc.prototype.isNotEmpty = function (value) {
	return typeof value !== 'undefined' && value !== null&& value !== "";
}

/**
 * 判断是否是数字类型
 */
JudgeFunc.prototype.isNumber = function (value) {
	return typeof value === 'number';
}

/**
 * 判断是否是日期
 */
JudgeFunc.prototype.isDate = function (value) {
	return toString.call(value) === '[object Date]';
}

/**
 * 判断是否是数组
 */
JudgeFunc.prototype.isArray = function (value) {
	try {
		return Array.isArray(value);
	} catch (e) {
		return false;
	}
}

/**
 *判断是否是非空数组 
 */
JudgeFunc.prototype.isHasValuesArray = function (value) {
	try {
		if (Array.isArray(value)) {
			return value.length > 0;
		} else {
			return false;
		}
	} catch (e) {
		return false;
	}
}

/**
 * 插入pushState
 */
JudgeFunc.prototype.pushStateToHistroy = function (state) {
	try {
		if (history.pushState && 'pushState' in history) {
			document.title = state.title;
			window.history.pushState(state, state.title, state.url);
			return true;
		} else {
			return false;
		}
	} catch (e) {
		return false;
	}
}

/**
 * 判断是否是Decimal
 */
JudgeFunc.prototype.isDecimal = function (num) {
	try {
		if (typeof num === 'number') {
			var numString = num.toString();
			if (numString.indexOf('.') > 0) {
				return parseInt(numString.substring(numString.indexOf(".") + 1)) > 0;
			} else {
				return false;
			}
		} else {
			return false;
		}
	} catch (e) {
		return false;
	}
}

/**
 * 判断是否是字符串
 */
JudgeFunc.prototype.isString = function (val) {
	return typeof val === 'string';
}

/**
 * 判断是否是Function
 */
JudgeFunc.prototype.isFunction = function (val) {
	return typeof val === 'function';
}

/**
 * 判断是否是文件
 */
JudgeFunc.prototype.isFile = function (obj) {
	return toString.call(obj) === '[object File]';
}

/**
 * 判断是否是MobilePhone
 */
JudgeFunc.prototype.isMobilePhone = function (val) {
	var patrn = /^((13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8})*$/;
	if (patrn.exec(val)&&val !="")
		return true;
	return false;
}

/**
 * 判断是否是Phone
 */
JudgeFunc.prototype.isPhone = function (val) {
	var patrn = /^((13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8})*$/;
	if (patrn.exec(val)&&val !="")
		return true;
	var patrn = /^(\d{3}-\d{8}|\d{3}-\d{7}|\d{4}-\d{7})*$/;
	if (patrn.exec(val)&&val !="")
		return true;
	return false;
}

/**
 * 判断是否是有效PassWord
 */
JudgeFunc.prototype.isPassWord = function (val) {
	var patrn = /[0-9 | A-Z | a-z]{6,18}/;
	if (patrn.exec(val)&&val !="")
		return true;
	return false;
}


/**
 * 判断是否是网址
 */
JudgeFunc.prototype.isWebAddress = function (val) {
	var strRegex = /(http(s)?:\/\/|^$)([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
	var patrn = new RegExp(strRegex);
	if (patrn.exec(val))
		return true;
	return false;
}

/*********************************ToolsFunc*******************************************************

/**
 * Form清空
 */
ToolsFunc.prototype.clearForm = function (FormId) {
	$("#" + FormId).find("input,textarea,select").each(function () {
		var type = $(this)[0].tagName.toLowerCase();
		var classText=$(this).attr("class");
		switch (type) {
		case "input":
		case "textarea":
			$(this).val("");
			if(classText!=undefined&&classText.indexOf("easyui")>-1){
				$(this).textbox('setValue', "");
			}
			break;
		case "select":
			$(this).val("");
			if(classText!=undefined&&classText.indexOf("easyui")>-1){
				$(this).textbox('setValue', "");
			}
			break;
		default:
		}
	});
}


/**
 * Form清空,ids中的保留
 */
ToolsFunc.prototype.clearFormByCondition = function (FormId,ids) {
	$("#" + FormId).find("input,textarea,select").each(function () {
		
		var type = $(this)[0].tagName.toLowerCase();
		var classText=$(this).attr("class");
		var id=$(this).attr("id");
		
		if($.inArray(id, ids)<0){
			switch (type) {
			case "input":
			case "textarea":
				$(this).val("");
				if(classText.indexOf("easyui")>-1){
					$(this).textbox('setValue', "");
				}
				break;
			case "select":
				$(this).val("");
				if(classText.indexOf("easyui")>-1){
					$(this).textbox('setValue', "");
				}
				break;
			default:
			}
		}
	});
}


/**
 * 计算
 */
ToolsFunc.prototype.calculateByExpression = function (expression, precision, isThrowError) {
	try {
		return parseFloat(eval(expression).toFixed(precision, !precision || precision === null || precision === undefined || precision === "" ? 0 : precision));
	} catch (e) {
		if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
			throw this.createErrorObject("对{0}进行解析计算出错，错误原因是：{1}", [expression, e.message]);
		}
	}
}
/**
 * 比较两个时间大小
 */
ToolsFunc.prototype.timeCompare = function (startTimeString, endTimeString, isThrowError) {
	try {
		return Date.parse(startTimeString) >= Date.parse(endTimeString);
	} catch (e) {
		if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
			throw this.createErrorObject("比较两个时间的大小时出错，错误原因是：{0}", [e.message]);
		}
	}
}

/**
 * 计算天数差的函数，通用
 */
ToolsFunc.prototype.dateDiff = function (startTimeString, endTimeString, isThrowError) {
	try {
		var aDate, oDate1, oDate2, iDays;
		aDate = sDate1.split("-");
		oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);  //转换为12-18-2002格式
		aDate = sDate2.split("-");
		oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
		iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24);  //把相差的毫秒数转换为天数
		return iDays;
	} catch (e) {
		if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
			throw this.createErrorObject("计算两个时间的差出错，错误原因是：{0}", [e.message]);
		}
	}
}

/**
 * 
 */
ToolsFunc.prototype.createStringSplitByCommaFromArray = function (rows, fieldName) {
	try {
		var retString = "";
		$.each(rows, function (index, item) {
			retString += "'" + item[fieldName] + "',";
		});
		retString = retString.replace(/,$/gi, "");
		return retString;
	} catch (e) {
		throw e;
	}
}

/**
 * 解码
 */
ToolsFunc.prototype.tryDecodeURIComponent = function (value, isThrowError) {
	try {
		return decodeURIComponent(value);
	} catch (e) {
		if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
			throw this.createErrorObject("对{0}解码时出现错误，错误原因是：{1}", [value, e.message]);
		}
	}
}

/**
 * js中获取地址参数
 */
ToolsFunc.prototype.queryString = function (value, isThrowError) {
	try {
		var sValue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"));
		return sValue ? sValue[1] : sValue
	} catch (e) {
		if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
			throw this.createErrorObject("js中获取地址参数，错误原因是：{1}", [value, e.message]);
		}
	}
}

/**
 * 删除url中指定的参数
 */
ToolsFunc.prototype.urlParamDe =function (url, name) {
	var sValue = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]*)(\&?)", "i"))
	if (sValue == null) { return url; }
	var reg = sValue[0];
	if (reg.substr(reg.length - 1, reg.length) == "&") {
		reg = reg.substr(0, reg.length - 1);
	}
	return url.replace(reg, "");
}

ToolsFunc.prototype.createErrorObject = function (formatString, error) {
	return new Error(formatString.format(error));
}

/**
 * 对象转换
 */
ToolsFunc.prototype.fromJson = function (json, isThrowError) {
	try {
		return this.isString(json) ? JSON.parse(json) : json;
	} catch (e) {
		if (isThrowError && typeof isThrowError === "boolean" && isThrowError === true) {
			throw this.createErrorObject("对{0}转换对象时出错，错误原因是：{1}", [json, e.message]);
		}
	}
}

/**
 * 时间格式化
 */
ToolsFunc.prototype.formatJsonDate = function (jsondate, format) {
	jsondate = jsondate + "";
	if (!/^\/Date[(].+[)]\/$/.test(jsondate)) 
		return jsondate.replace("T", " ");
	jsondate = jsondate.replace("/Date(", "").replace(")/", "");
	if (jsondate.indexOf("+") > 0) {
		jsondate = jsondate.substring(0, jsondate.indexOf("+"));
	}
	else if (jsondate.indexOf("-") > 0) {
		jsondate = jsondate.substring(0, jsondate.indexOf("-"));
	}
	var datetime = new Date(parseInt(jsondate, 10));
	if (!format) format = "yyyy-MM-dd";
	return datetime.Format(format);
}

/**
 *  date为 英文开头格式
 *  formatDate(date,"yyyy-MM-dd HH:mm")
 */
ToolsFunc.prototype.formatDate=function(now,mask){
	if(toString.call(now) !== '[object Date]'){
		now=new Date(now);
	}
	var d = now;
	var zeroize = function (value, length)
	{
		if (!length) length = 2;
		value = String(value);
		for (var i = 0, zeros = ''; i < (length - value.length); i++)
		{
			zeros += '0';
		}
		return zeros + value;
	};

	return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0)
			{
		switch ($0)
		{
		case 'd': return d.getDate();
		case 'dd': return zeroize(d.getDate());
		case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
		case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
		case 'M': return d.getMonth() + 1;
		case 'MM': return zeroize(d.getMonth() + 1);
		case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
		case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
		case 'yy': return String(d.getFullYear()).substr(2);
		case 'yyyy': return d.getFullYear();
		case 'h': return d.getHours() % 12 || 12;
		case 'hh': return zeroize(d.getHours() % 12 || 12);
		case 'H': return d.getHours();
		case 'HH': return zeroize(d.getHours());
		case 'm': return d.getMinutes();
		case 'mm': return zeroize(d.getMinutes());
		case 's': return d.getSeconds();
		case 'ss': return zeroize(d.getSeconds());
		case 'l': return zeroize(d.getMilliseconds(), 3);
		case 'L': var m = d.getMilliseconds();
		if (m > 99) m = Math.round(m / 10);
		return zeroize(m);
		case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
		case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
		case 'Z': return d.toUTCString().match(/[A-Z]+$/);
		// Return quoted strings with the surrounding quotes removed
		default: return $0.substr(1, $0.length - 2);
		}
			});
};

/**
 * 随机数
 */
ToolsFunc.prototype.randomBy = function (under, over) {
	switch (arguments.length) {
	case 1: return parseInt(Math.random() * under + 1);
	case 2: return parseInt(Math.random() * (over - under + 1) + under);
	default: return 0;
	}
}

/** 
 * 将数值四舍五入(保留2位小数)后格式化成金额形式 
 * @param number 数值(Number或者String) 
 * @return 金额格式的字符串,如'1,234,567.45' 
 * @type String 
 */  
ToolsFunc.prototype.formatMoney=function (number) {  
	number = number.toString().replace(/\$|\,/g,'');    
	if(isNaN(number))    
		number = "0";    
	var sign = (number == (number = Math.abs(number)));    
	number = Math.floor(number*100+0.50000000001);    
	var cents =number%100;    
	number = Math.floor(number/100).toString();    
	if(cents<10)    
		cents = "0" + cents;    
	for (var i = 0; i < Math.floor((number.length-(1+i))/3); i++)    
		number = number.substring(0,number.length-(4*i+3))+','+    
		number.substring(number.length-(4*i+3));    
	return (((sign)?'':'-') + number + '.' + cents);  
}  

/**
 * 字符串format扩展
 */
String.prototype.format = function (args) {
	var result = this;
	if (arguments.length > 0) {
		if (arguments.length == 1 && typeof (args) == "object") {
			for (var key in args) {
				if (args[key] != undefined) {
					var reg = new RegExp("({)" + key + "(})", "g");
					result = result.replace(reg, args[key]);
				}
			}
		}
		else {
			for (var i = 0; i < arguments.length; i++) {
				if (arguments[i] != undefined) {
					var reg = new RegExp("({)" + i + "(})", "g");
					result = result.replace(reg, arguments[i]);
				}
			}
		}
	}
	return result;
}


/*********************************ToolsImage****************************************
/*
 * file转base编码，并压缩
 * file
 * 用法如下
    $.FileToBase64(file, function(base64) {
        $.AutoResizeImage(base64, 0, 0, function (zipbase64) {
        });
    });
 */
ToolsImage.prototype.fileToBase64 = function (file, fn) {
	//利用html5转base64
	if ("FileReader" in window) {
		var reader = new FileReader();
		reader.onload = function (e) {
			if (fn) {
				return fn(this.result);
			}
		};
		reader.readAsDataURL(file);
	}
};

/*
 * base64图像压缩
 * base64:base64编码
 * maxWidth:最大图像宽度，0为auto
 * maxHeight:最大图像高度，0为auto
 * fn(base64):压缩完成后回调，返回base64编码
 * 用法如下
    $.AutoResizeImage(base64, 0, 0, function (zipbase64) {
    });
 */
ToolsImage.prototype.autoResizeImage = function (base64, maxWidth, maxHeight, fn) {
	//开始压缩图片
	var img = new Image();
	img.crossOrigin = "Anonymous";
	img.onload = function () {
		//获取当前最合适的图像比率
		var hRatio;
		var wRatio;
		var Ratio = 1;
		var w = img.width;
		var h = img.height;
		wRatio = maxWidth / w;
		hRatio = maxHeight / h;
		if (maxWidth == 0 && maxHeight == 0) {
			Ratio = 1;
		} else if (maxWidth == 0) { //
			if (hRatio < 1) Ratio = hRatio;
		} else if (maxHeight == 0) {
			if (wRatio < 1) Ratio = wRatio;
		} else if (wRatio < 1 || hRatio < 1) {
			Ratio = (wRatio <= hRatio ? wRatio : hRatio);
		}
		if (Ratio < 1) {
			w = w * Ratio;
			h = h * Ratio;
		}

		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext("2d");
		ctx.clearRect(0, 0, canvas.width, canvas.height); // canvas清屏

		//缩小
		img.width = w;
		img.height = h;

		//重置canvans宽高
		canvas.width = img.width;
		canvas.height = img.height;

		ctx.drawImage(img, 0, 0, img.width, img.height); // 将图像绘制到canvas上
		var zipbase64 = canvas.toDataURL('image/png'); //输出base64
		//if (img.size > (1024 * 1024 * 0.5)) {
		//    alert("图片太大，压缩后仍然超过0.5M!");
		//    return;
		//}
		fn(zipbase64, img.width, img.height);
	};
	img.src = base64;
	if (img.complete || img.complete === undefined) {
		img.src = "";
		img.src = base64;
	}
};
